package com.webull.information.center.carwler.task.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.cms.client.model.YgTickerMap;
import com.webull.cms.client.service.YgTickerMapService;
import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.StockConfig;
import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;
import com.webull.information.center.carwler.common.util.news.BloombergNewsListUitl;
import com.webull.information.center.carwler.common.util.news.BloombergNewsListUitl.BloomergItem;
import com.webull.information.center.carwler.task.support.StockConfigSupport;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.center.common.constants.UrlConstants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;

/**
 * 美国彭博
 * 
 * @author smj
 *
 */
@Component
public class StockBloombergNewsHandler {

	protected final Logger logger = LogManager.getLogger(getClass());
	private static String bloomberg_lang = Constants.lang_en;// 新浪语言版本
	private @Autowired BloombergNewsListUitl bloombergNewsListUitl;

	private @Autowired StockConfigSupport stockConfigSupport;
	private @Autowired YgTickerMapService ygTickerMapService;
	private @Autowired
    TikcerNewsProcessor tikcerNewsProcessor;

	private String googleSymbol(Integer tickerId) {
		YgTickerMap param = new YgTickerMap();
		param.setTickerId(tickerId);
		return Optional.ofNullable(ygTickerMapService.search(param))//
				.filter(v -> v.size() >= 1).map(v -> v.get(0).getSymbol()).orElse(null);
	}

	public void handlerByStockTitle4Bloomerg(StockTitle stockTitle) {
		String bbSymbol = Optional.ofNullable(googleSymbol(stockTitle.getTickerId())).orElse(stockTitle.getSymbol());
		StockConfig stockConfig = stockConfigSupport.getStockConfig(stockTitle, "cnbc_en", bloomberg_lang);
		String bbRegionAlias = stockTitle.getBbRegionAlias();
		String newsProfile = getBloombergProfileUrl(stockTitle.getRegionId(), bbSymbol, bbRegionAlias);
		processBloomergList(stockConfig, stockTitle, newsProfile);
	}

	private void processBloomergList(StockConfig stockConfig, StockTitle stockTitle, String newsProfile) {
		try {
			List<Date> times = new ArrayList<>();
			Date lastPush = stockConfig.getCollectTime();
			/**
			 * 获取标的物新闻首页列表
			 */
			List<BloomergItem> newsList = bloombergNewsListUitl.parseNewsList(newsProfile);
			//
			entrie: for (int i = 0; newsList != null && i < newsList.size(); i++) {
				try {
					BloomergItem item = newsList.get(i);
					Date push = item.getNewsTime();
					if (push == null) {
						logger.warn("-processSinaList stockTitle:{}, url:{} BloomergItem:{}, push can't be parse!!",
								stockTitle, newsProfile, item);
						continue entrie;
					}

					if (lastPush == null || DateUtils.isSameDay(push, new Date()) || push.after(lastPush)) {
						times.add(push);
						processBloomergNews(stockTitle, item);
					}
				} catch (Exception e) {
					logger.warn(e);
					break entrie;
				}
			}

			if (!times.isEmpty()) {
				tikcerNewsProcessor.updateStockConfig(stockConfig,times);
				stockConfigSupport.updateById(stockConfig);
			}

		} catch (Exception e) {
			stockConfig.setCollectNumber(-99);
			stockConfigSupport.updateById(stockConfig);
			logger.error("processRss(Date lastPush, StockTitle stockTitle, String compFinanceRss)", e);
		}
	}

	private void processBloomergNews(StockTitle stockTitle, BloomergItem item) throws Exception {
		String title = item.getTitle();
		String link = item.getLink();
		// SyndContent description = entry.getDescription();
		NewsInformation info = new NewsInformation();// produce(doc);
		info.setCollectSource(News.CollectSource.Bloomb);
		info.setSiteType(News.SiteType.PIRORIT);
		info.setTitle(title);
		info.setRegionId(stockTitle.getRegionId());

		info.setNewsTime(item.getNewsTime());
		info.setUrl(link);
		info.setLanguage(bloomberg_lang);

		info.setSourceName(item.getSource());
		String md5 = HttpJsoupClient.finishingMd5Url(link);
		info.setUrlMd5(md5);

		tikcerNewsProcessor.bindTargetNewsRecord(info, stockTitle.getTickerId(), NewsRelType.ticker);
	}

	/**
	 * 转换成CNBC的新闻列表url
	 *
	 * <pre>
	 * 目前只支持美股
	 * </pre>
	 * @param regionId
	 * @param symbol
	 * @param bbRegionAlias
	 * @return
	 */
	private String getBloombergProfileUrl(Integer regionId, String symbol, String bbRegionAlias) {
		if (Integer.valueOf(2).equals(regionId)) // 香港的去掉前面的0
			symbol = StringUtils.stripStart(symbol, "0");
		return UrlConstants.bloombergNewsUnitUrl + symbol + ":" + bbRegionAlias;
	}

}
